#ifndef __THREADHPP
#include <iostream>
#include <pthread.h>
#include <functional>
#include <string>
namespace ThreadModule
{
    template <typename T>
    using func_t = std::function<void(T)>;

    template <class T>
    class Thread
    {
    public:
        void Excute()
        {
            _fun(_data);
        }
    public:
        Thread(func_t<T> fun, T data, const std::string& name = "none-name", bool stop = true)
        :_fun(fun), _data(data), _name(name), _stop(stop)
        {}
        ~Thread()
        {}

        static void* threadroutine(void* arg)
        {
            Thread<T>* self = static_cast<Thread<T>*>(arg);
            self->Excute(); //static函数没有this指针，不能直接调用成员_fun
            return nullptr;
        }
        
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (n == 0)
            {
                _stop = false;
            }
            else
            {
                _stop = true;
            }
            return _stop;
        }

        void Stop()
        {
            _stop = true;
        }

        void Join()
        {   
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        std::string name()
        {
            return _name;
        }

        pthread_t get_id()
        {
            return _tid;
        }
    private:
        pthread_t _tid;
        std::string _name;
        func_t<T> _fun; 
        T _data;       //让所有线程访问同一个全局变量
        bool _stop;
    };

}

#define __THREADHPP
#endif